//富文本编辑器组件
import React, { useEffect, useState } from "react";
import { Editor } from "react-draft-wysiwyg";
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
import { EditorState, convertToRaw, ContentState } from 'draft-js';
import draftToHtml from "draftjs-to-html";
import htmlToDraft from 'html-to-draftjs'
/* 安装了缺失的 draftjs-to-html 依赖包（版本 ^0.9.1）
同时安装了 immutable 依赖包，这是 react-draft-wysiwyg 所需要的 */

export default function NewsEditor({getContent,content}) {
  const [editorState, setEditorState] = useState('');
  //相关方法从github中查询文档可知
  useEffect(()=>{
    //如果content不存在就转换
    if(content){
      console.log(content);
      const html = content;
      const contentBlock = htmlToDraft(html);
      if (contentBlock) {
        const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks);
        const editorState = EditorState.createWithContent(contentState);
        setEditorState(editorState);
      }
    }
  },[])
  return (
    <div style={{ width: "100%" }}>
      <Editor
        editorState={editorState}
        toolbarClassName="toolbarClassName"
        wrapperClassName="wrapperClassName"
        editorClassName="editorClassName"
        onEditorStateChange={(editorState) => setEditorState(editorState)}
        //失去焦点时拿到状态 并将draft转译为html
        onBlur={() => {
          getContent(
            draftToHtml(convertToRaw(editorState.getCurrentContent()))
          );
          // console.log(editorState.getCurrentContent())
        }}
      />
    </div>
  );
}
